package com.ddstation.home_page.service;

import com.ddstation.common.util.CheckUtil;
import com.ddstation.crm.institution.mapper.DtHealthManageInstitutionMapper;
import com.ddstation.home_page.entity.DtInvsMessageQueueEntity;
import com.ddstation.home_page.mapper.DtInvsMessageQueueMapper;
import com.ddstation.home_page.mapper.HomePageMapper;
import com.ddstation.home_page.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class HomePageServiceImpl implements HomePageService {


	public List<MapModel> getRealTimeMonitorList(String invsInstitutionId){
		return dtInvsMessageQueueMapper.selectInvsMonitorMessageQueue(invsInstitutionId);
	}

	// 查询异常（污水、消毒、医废处置,异地执业）行为数·累积数
	public HpTotalResModel getVarious(HpCommonParModel _p){
		
		HpTotalResModel mod = new HpTotalResModel();
		
		HpCommonParModel _pViolate = new HpCommonParModel();//查询卫生警报用参数
		BeanUtils.copyProperties(_p, _pViolate);
		HpCommonParModel _pWarings = new HpCommonParModel();//查询卫生警报用参数
		BeanUtils.copyProperties(_p, _pWarings);
		HpCommonParModel _pRemote = new HpCommonParModel();//查询异地执业参数
		BeanUtils.copyProperties(_p, _pRemote);
		HpCommonParModel _pThreeDay = new HpCommonParModel();//查询异地执业参数
		BeanUtils.copyProperties(_p, _pThreeDay);
		
		Integer[] violateTypes = {40};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
		_pViolate.setBusinessTypeList(violateTypes);
		Integer[] warningTypes = {10,20,30};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
		_pWarings.setBusinessTypeList(warningTypes);
		Integer[] remoteTypes = {60};//@60：异地执业
		_pRemote.setBusinessTypeList(remoteTypes);
		Integer[] threeDayTypes = {70};//@70:三天为开处方
		_pThreeDay.setBusinessTypeList(threeDayTypes);
		// 不良执业行为分类 
		List<NameValueModel>  violatePie = homePageMapper.selectWarningClassify(_pViolate);
        mod.setViolatePie(violatePie);
        // 警告统计图表
        List<NameValueModel> warningPie = homePageMapper.selectWarningClassify(_pWarings);
		mod.setWarningPie(warningPie);
		// 监控的机构数 
		mod.setMonitoringInstitutionCnt(homePageMapper.selectMonitoringInstitutionCnt(_p.getInvsInstitutionId()));
		// 异常医疗机构 
		mod.setAbnormalInstitutionCnt( homePageMapper.selectAbnormalInstitutions(_pViolate));
		// 监控电子处方数  左2框 
		mod.setMonitoringPrescriptionCnt( homePageMapper.selectMonitoringPrescriptionCnt(_pViolate));;
		// 处方违规行为数  左2框 
		int violates = homePageMapper.selectAbnormalCnt2(_pViolate);
		mod.setViolates(violates);
		// 累计处方违规行为数  左2框 
		_pViolate.setDtFrom(null);
		_pViolate.setDtTo(null);
		int violateCnt= homePageMapper.selectAbnormalCnt2(_pViolate);
		mod.setViolateCnt(violateCnt);
		// 卫生异常行为报警数  右1  
		int warnings = homePageMapper.selectAbnormalCnt(_pWarings);
		mod.setWarnings(warnings);
		// 累计卫生异常行为数  右1 
		_pWarings.setDtFrom(null);
		_pWarings.setDtTo(null);
		int warningCnt = homePageMapper.selectAbnormalCnt(_pWarings);
		mod.setWarningCnt(warningCnt);
		// 异地执业异常数 右1
		int remotes=homePageMapper.selectAbnormalCnt(_pRemote);
		mod.setRemotes(remotes);
		_pWarings.setDtFrom(null);
		_pWarings.setDtTo(null);
		int remoteCnt=homePageMapper.selectAbnormalCnt(_pRemote);
		mod.setRemoteCnt(remoteCnt);
		//三天未开处方
		int threeDays=homePageMapper.selectAbnormalCnt(_pThreeDay);
		mod.setThreeDays(threeDays);
		_pThreeDay.setDtFrom(null);
		_pThreeDay.setDtTo(null);
		int threeDayCnt=homePageMapper.selectAbnormalCnt(_pThreeDay);
		mod.setThreeDayCnt(threeDayCnt);
		// 异常事项 左1框       
		mod.setAbnormality(mod.getViolates());
		// 累计异常事项 左1框 
		mod.setAbnormalityCnt(mod.getViolateCnt());
		//处方违规 月趋势
		List<NameValueModel> violateTimeLine=this.getTimeLine(_pViolate);
		mod.setViolateTimeLine(violateTimeLine);
		//卫生警告 月趋势
		List<NameValueModel> warningTimeLine=this.getTimeLine(_pWarings);
		mod.setWarningTimeLine(warningTimeLine);
		return mod;
	}
	
	// 不良执业行为散点图数据查询
	@Override
	@Transactional(rollbackFor=Exception.class)
	public List<MapModel> getBadPracticingTown(HpCommonParModel _p){
		
		
//		List<MapModel> listBadPracticing = homePageMapper.selectBadPracticingTown(_p);
//		for (MapModel a:listBadPracticing){
//			a.setValue(50);//红色表示
//		}
//		List<MapModel> badBehaviorList = this.getBadBehaviorTown(_p);
//		for (MapModel a:badBehaviorList){
//			a.setValue(500);//黄色表示
//		}
//
//		listBadPracticing.addAll(badBehaviorList);

		List<MapModel> listBadPracticing = new ArrayList<MapModel>();
//		MapModel a  = new MapModel();
//		a.setLatitude(30.1606F);
//		a.setLongitude(119.3019F);
//		a.setTown("10003");
//		a.setValue(500);
//		listBadPracticing.add(a);

//		List<DtInvsMessageQueueEntity> messageList = dtInvsMessageQueueService.getMessageQueue(_p.getUa());
		List<DtInvsMessageQueueEntity> messageList=new ArrayList<>();
		List<MapModel> mapModelList = dtInvsMessageQueueService.getMapModelByMessageQueues(_p,messageList);
		listBadPracticing.addAll(mapModelList);
		return listBadPracticing;
	}
	
	// 异常行为警告散点图数据
	@Override
	@Transactional(readOnly=true)
	public List<MapModel> getBadBehaviorTown(HpCommonParModel _p){
		
//        SearchParModel _in = new SearchParModel();
//        _in.setInvsInstitutionId(_p.getInvsInstitutionId());
//        _in.setDateFrom(_p.getViolateDtFrom());
//        _in.setDateTo(_p.getViolateDtTo());
//        
//		return homePageMapper.selectAbnormalTown(new ArrayList<>(set));
		return new ArrayList<>();
	}
	
	// 半年趋势[处方 + 异常警告]
	@Override
	@Transactional(readOnly=true)
	public List<NameValueModel> getTimeLine(HpCommonParModel _p){
		List<NameValueModel> listOut = this.getFromToRange(_p.getFromYm(),_p.getToYm());
		
		List<NameValueModel> aList = homePageMapper.selectTimeLine(_p);
		for ( NameValueModel _one: listOut){
			// 匹配到对应的月
			List<NameValueModel> fillerList = aList.stream().filter(
						a->a.getName().equals(_one.getName()))
					.collect(Collectors.toList());
			if ( fillerList != null && fillerList.size() > 0  ){
				_one.setValue(fillerList.get(0).getValue());
			}
		}
		return listOut;
	}

	private List<NameValueModel> getFromToRange(String fromYm,String toYm){
		List<NameValueModel> listOut = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		// 循环生成月份
		try {
			Date d1 = sdf.parse(fromYm);
			Date d2 = sdf.parse(toYm);//定义结束日期
			
			Calendar dd = Calendar.getInstance();//定义日期实例

			dd.setTime(d1);//设置日期起始时间
			
			do {//判断是否到结束日期
				NameValueModel a = new NameValueModel();
				a.setName(sdf.format(dd.getTime()));// 月份
				listOut.add(a);
				dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
			} while ( dd.getTime().compareTo(d2)<=0 ); //一直循环到结束月
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listOut;
	}
	
	// 违规诊所数[半年趋势]
	public List<NameValueModel> getBadInstitutionsTimeLine(String invsInstitutionId,String fromYm,String toYm){
		// 根据年月、机构ID去重
		return new ArrayList<>();
	}

	//按机构类别归类统计
	public HomePageDataModel statisticsByTypeFirst(String id, HpCommonParModel _p){
		HomePageDataModel homePageDataModel = new HomePageDataModel();
		//规定时间内异常数据
		List<DailyStatisticsModel> dailyStatisticsList = dtHealthManageInstitutionMapper.statisticsByTypeFirst(id, _p.getDtFrom(), _p.getDtTo());
		//规定时间内台账/处方监管数
		DailyStatisticsModel dailyStatisticsPresModel = dtHealthManageInstitutionMapper.statisticsDailyPres(id,  _p.getDtFrom(), _p.getDtTo());
		DailyStatisticsModel dailyStatisticsActionModel = dtHealthManageInstitutionMapper.statisticsDailyAction(id,  _p.getDtFrom(), _p.getDtTo());
		//汇总map
		DailyStatisticsModel allDaily = new DailyStatisticsModel();
		//左上 机构分类map
		InstitutionStatisticsModel institutionStatisticsModel = new InstitutionStatisticsModel();
		//右上1 处方异常集合
		List<NameValueModel> presDailyPie = new ArrayList<>();
		//右上2 台账异常集合
		List<NameValueModel> actionDailyPie = new ArrayList<>();
		for(DailyStatisticsModel dailyStatistics:dailyStatisticsList){
			//累计汇总值
			allDaily.setInstitutionCount(allDaily.getInstitutionCount()+dailyStatistics.getInstitutionCount());
			allDaily.setPresDailyCount(allDaily.getPresDailyCount()+dailyStatistics.getPresDailyCount());
			allDaily.setActionDailyCount(allDaily.getActionDailyCount()+dailyStatistics.getActionDailyCount());
			if("01".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy01(dailyStatistics.getInstitutionCount());
			}else if("02".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy02(dailyStatistics.getInstitutionCount());
			}else if("03".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy03(dailyStatistics.getInstitutionCount());
			}else if("04".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy04(dailyStatistics.getInstitutionCount());
			}else if("05".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy05(dailyStatistics.getInstitutionCount());
			}else if("06".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy06(dailyStatistics.getInstitutionCount());
			}else if("07".equals(dailyStatistics.getValueCode())){
				institutionStatisticsModel.setInstitutionCntBy07(dailyStatistics.getInstitutionCount());
			}
			//处方异常
			NameValueModel presDaily = new NameValueModel();
			if(!CheckUtil.isEmpty(dailyStatistics.getValueCode())||!CheckUtil.isEmpty(dailyStatistics.getAbbreviation()))
			{
				presDaily.setName(dailyStatistics.getAbbreviation());
				presDaily.setValue(dailyStatistics.getPresDailyCount());
				presDailyPie.add(presDaily);
				//台账异常
				NameValueModel actionDaily = new NameValueModel();
				actionDaily.setName(dailyStatistics.getAbbreviation());
				actionDaily.setValue(dailyStatistics.getActionDailyCount());
				actionDailyPie.add(actionDaily);
			}
		}
		//总机构数
		institutionStatisticsModel.setAllInstitutionCnt(allDaily.getInstitutionCount());
		//左上 机构类别
		homePageDataModel.setInstitutionStatistics(institutionStatisticsModel);
		//右上1 处方异常集合
		homePageDataModel.setPresDailyPie(presDailyPie);
		//右上2 台账异常集合
		homePageDataModel.setActionDailyPie(actionDailyPie);
		//规定时间内处方监管
		AllPartModel datePresCnt = new AllPartModel();
		datePresCnt.setAll(dailyStatisticsPresModel.getPresDailyCount());
		datePresCnt.setPart(allDaily.getPresDailyCount());
		homePageDataModel.setDatePresCnt(datePresCnt);
		//规定时间内台账监管
		AllPartModel dateActionCnt = new AllPartModel();
		dateActionCnt.setAll(dailyStatisticsActionModel.getActionDailyCount());
		dateActionCnt.setPart(allDaily.getActionDailyCount());
		homePageDataModel.setDateActionCnt(dateActionCnt);
		//异常处理（）
		AllPartModel dateErrorHandleCnt = dtHealthManageInstitutionMapper.statisticsErrorHandle(id, _p.getDtFrom(), _p.getDtTo());
		homePageDataModel.setDateErrorHandleCnt(dateErrorHandleCnt);
		return homePageDataModel;
	}

	@Override
	public HomePageDataModel statisticsByType(String id, HpCommonParModel _p) {
		HomePageDataModel homePageDataModel = new HomePageDataModel();
		//全部台账/处方监管数
		DailyStatisticsModel allTimeDailyStatisticsPresModel = dtHealthManageInstitutionMapper.statisticsDailyPres(id, null,null);
		DailyStatisticsModel allTimeDailyStatisticsActionModel = dtHealthManageInstitutionMapper.statisticsDailyAction(id, null,null);
		//累计处方
		homePageDataModel.setAllPresCnt(allTimeDailyStatisticsPresModel.getPresDailyCount());
		//累计台账
		homePageDataModel.setAllActionCnt(allTimeDailyStatisticsActionModel.getActionDailyCount());
		//处方违规类型分布（右下）
		List<NameValueModel> presDailyByType = dtHealthManageInstitutionMapper.presDailyByType(id, _p.getDtFrom(), _p.getDtTo());
		homePageDataModel.setPresDailyByType(presDailyByType);
		HpCommonParModel _pViolate = new HpCommonParModel();//查询卫生警报用参数
		BeanUtils.copyProperties(_p, _pViolate);
		HpCommonParModel _pWarings = new HpCommonParModel();//查询卫生警报用参数
		BeanUtils.copyProperties(_p, _pWarings);
		Integer[] violateTypes = {40};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
		_pViolate.setBusinessTypeList(violateTypes);
		Integer[] warningTypes = {10,20,30};//@10：消毒登记 @20：医废登记 @30：检测审查 @40：处方违规
		_pWarings.setBusinessTypeList(warningTypes);
		//处方违规 月趋势
		List<NameValueModel> violateTimeLine=this.getTimeLine2(_pViolate);
		homePageDataModel.setViolateTimeLine(violateTimeLine);
		//卫生警告 月趋势
		List<NameValueModel> warningTimeLine=this.getTimeLine2(_pWarings);
		homePageDataModel.setWarningTimeLine(warningTimeLine);
		return homePageDataModel;
	}

	// 半年趋势[处方 + 异常警告]
	@Transactional(readOnly=true)
	public List<NameValueModel> getTimeLine2(HpCommonParModel _p){
		List<NameValueModel> aList = homePageMapper.selectTimeLine(_p);
		return aList;
	}

	@Inject private HomePageMapper homePageMapper;
	@Inject private DtInvsMessageQueueService dtInvsMessageQueueService;
	@Inject private DtInvsMessageQueueMapper dtInvsMessageQueueMapper;
	@Inject private DtHealthManageInstitutionMapper dtHealthManageInstitutionMapper;
}

